//
//  UITextField+ValidaType.m
//  shunlianPower2
//
//  Created by 陈镇 on 2018/11/16.
//  Copyright © 2018年 顺联网络. All rights reserved.
//

#import "UITextField+ValidaType.h"
#import "NSString+SLAdd.h"
#import <Objc/runtime.h>
#import <QMUIKit/QMUIKit.h>
@implementation UITextField (ValidaType)

-(SLTextFieldType)type{
    return ((SLTextFieldType)[objc_getAssociatedObject(self, _cmd) integerValue]);
}
-(void)setType:(SLTextFieldType)type{
    objc_setAssociatedObject(self, @selector(type), @(type), OBJC_ASSOCIATION_RETAIN);
    [self setTextFileAttribute:type];
}

-(void)setTextFileAttribute:(SLTextFieldType)type{
    switch (type) {
        case SLTextFieldTypeDefault:{
            
        }break;
        case SLTextFieldTypeMobile:{
            self.keyboardType = UIKeyboardTypePhonePad;
        }break;
        case SLTextFieldTypeNumber:{
            self.keyboardType = UIKeyboardTypePhonePad;
        }break;
        default:
            break;
    }
}


/** 验证类型进行处理 */
- (BOOL)validaShouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    switch (self.type) {
        case SLTextFieldTypeDefault:{
            
        }break;
        case SLTextFieldTypeMobile:{// 手机号验证 基本验证
                if (![string sl_isValidNumber]) {
                    return NO;
                }
                NSString *tmps = [NSString stringWithFormat:@"%@%@",self.text,string];
                if ([string isEqualToString:@""] && tmps.length>0) {
                    tmps = [tmps substringWithRange:NSMakeRange(0, tmps.length - 1)];
                }
                tmps = [tmps qmui_trimAllWhiteSpace];
                if (tmps.length<=3) {
                    self.text = tmps;
                }else if(tmps.length<=7){
                    NSString *one = [tmps substringWithRange:NSMakeRange(0, 3)];
                    NSString *tow = [tmps substringWithRange:NSMakeRange(3, tmps.length-3)];
                    self.text = [NSString stringWithFormat:@"%@ %@",one,tow];
                }else if(tmps.length<=11){
                    NSString *one = [tmps substringWithRange:NSMakeRange(0, 3)];
                    NSString *tow= [tmps substringWithRange:NSMakeRange(3, 4)];
                    NSString *three = [tmps substringWithRange:NSMakeRange(7, tmps.length-7)];
                    self.text = [NSString stringWithFormat:@"%@ %@ %@",one,tow,three];
                }
                return NO;
        }break;
        case SLTextFieldTypeNumber:{
            
        }break;
        default:
            return YES;
            break;
    }
    return YES;
}
@end
